/* Copyright 2011 Tobias Marschall, Email: tm@cwi.nl 
 * 
 * This file is part of string-cover.
 *
 * string-cover is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * string-cover is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with string-cover.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <cassert>
#include <iostream>
#include <boost/tokenizer.hpp>

#include "StringBasedWeightFunction.h"

using namespace std;
using namespace boost;

StringBasedWeightFunction::StringBasedWeightFunction(std::ifstream& f, double default_weight) : default_weight(default_weight) {
	assert(f.is_open());
	is_integer = true;
	char_separator<char> sep(" \t");
	int n = 0;
	while(!f.eof()) {
		string line;
		getline(f, line);
		n += 1;
		if (line.empty()) continue;
		tokenizer<char_separator<char> > t(line, sep);
		vector<string> tokens(t.begin(), t.end());
		if (tokens.size()!=2) {
			cerr << "Error reading weight function from file. Offending line: " << n << endl;
			exit(1);
		}
		double weight = atof(tokens[1].c_str());
		if (tokens[1].find(".") != string::npos) {
			is_integer = false;
		}
		weight_by_string[tokens[0]] = weight;
	}
	cout << "Read weight table with " << weight_by_string.size() << " entries; default weight is " << default_weight << "." << endl;
	cout << "Integer weights: " << (is_integer?"yes":"no") << endl;
}



StringBasedWeightFunction::~StringBasedWeightFunction()
{
}


double StringBasedWeightFunction::getWeight(string s) const {
	if (weight_by_string.count(s)) return weight_by_string.at(s);
	else return default_weight;
}



bool StringBasedWeightFunction::isInteger() const {
	return is_integer;
}
